import { queryFakeList, removeFakeList, addFakeList, updateFakeList } from '@/services/api';
import * as articleService from '../services/category'
import * as routerRedux from "react-router-redux";
import {message} from "antd";

export default {
  namespace: 'category',
  state: {
    list: [],
    detail:{}
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(articleService.allCategory, payload);
      if(!response){
        return false;
      }
      if(response.code=="SUCCESS"){
        yield put({
          type: 'queryList',
          payload: Array.isArray(response.data) ? response.data : [],
        });
      }
    },
    *save({ payload}, { call, put }) {
      const response = yield call(articleService.saveCategory, payload);
      if(!response){
        return false;
      }
      if(response.code=="SUCCESS"){
        message.success('操作成功');
        yield put({
          type: 'fetch',
          payload: {type:payload.type},
        });
      }else{
        message.error(response.msg||"error_1")
      }
    },
    *delete({ payload }, { call, put }){
      const response = yield call(articleService.deleteCategory, payload);
      if(response.code=="SUCCESS"){
        message.success("删除成功");
        yield put({
          type: 'fetch',
          payload: {type:payload.type},
        });
      }else{
        alert(response.msg||"error_1")
      }

    },
    *submit({ payload }, { call, put }) {
      let callback;
      if (payload.id) {
        callback = Object.keys(payload).length === 1 ? removeFakeList : updateFakeList;
      } else {
        callback = addFakeList;
      }
      const response = yield call(callback, payload); // post
      yield put({
        type: 'queryList',
        payload: response,
      });
    },
  },
  reducers: {
    queryList(state, action) {
      return {
        ...state,
        list: action.payload,
      };
    },
    queryDetail(state, action) {
      return {
        ...state,
        detail: action.payload,
      };
    },
  }
};
